package cn.com.maven.designpattern.singleton;

/**
 * 懒汉模式，instance为null时创建新对象，getInstance使用synchronized，线程安全
 * @Author YongQiang
 * @Date 2021/5/18 10:17
 * @Version 1.0
 */
public class LazySingletonSafe {
    private static LazySingletonSafe instance = null;

    private LazySingletonSafe(){

    }

    public static synchronized LazySingletonSafe getInstance(){
        if (instance == null) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            instance = new LazySingletonSafe();
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> System.out.println(LazySingletonSafe.getInstance())).start();
        }
    }
}
